import axios, { type AxiosRequestConfig } from "axios";
import { ElMessage } from "element-plus";


const BASE_URL =
  process.env.NODE_ENV === "production" ? "/api" : "http://127.0.0.1:8000/api";

const http = axios.create({
  baseURL: 'http://113.44.40.109:8000/api',
});

// 请求拦截器
http.interceptors.request.use(
  (conf) => {
    if (localStorage.getItem("token")) {
      conf.headers.Authorization = `Bearer ${localStorage.getItem("token")}`;
    }
    return conf;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (res) => {
    return res;
  },
  (err) => {
    if (err.response.status === 422) {
      // 跳转到403页面
      ElMessage.error(err.message);
    }
    if (err.response.status === 401) {
      // 跳转到登录页
      window.location.href = "/login";
    }
    return Promise.reject(err);
  }
);

//<T>代表这个T在这个函数的作用域上面
export default <T>(conf: AxiosRequestConfig) => {
  return http(conf).then((res) => {
    return res.data as T;
  });
};
